import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const isLoggedIn = ref(false)
  const userInfo = ref(null)
  const token = ref(null)
  
  // Actions
  const login = (userToken, user) => {
    token.value = userToken
    userInfo.value = user
    isLoggedIn.value = true
    
    // 保存到localStorage
    localStorage.setItem('token', userToken)
    localStorage.setItem('user_info', JSON.stringify(user))
  }
  
  const logout = () => {
    token.value = null
    userInfo.value = null
    isLoggedIn.value = false
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('user_info')
  }
  
  const checkAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user_info')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      try {
        userInfo.value = JSON.parse(storedUser)
        isLoggedIn.value = true
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  }
  
  // 初始化检查
  checkAuth()
  
  return {
    isLoggedIn,
    userInfo,
    token,
    login,
    logout,
    checkAuth
  }
})

